var xmlhttp;
var intervalId;
var field;

window.onload = function() {
	field = document.getElementsByClassName("field").item(0);
	field.style.width = 800 + "px";
	field.style.height = 600 + "px";
};

function create() {
	field.innerHTML = "";
	var balls = new Array();
	for (var i = 0; i < 5; ++i)
		balls[i] = createBall();	
	xmlhttp = getXMLHTTP(function() {
		if (this.readyState==4 && this.status==200) {
			drawBalls(balls);
			console.log(this.responseText);
			send("pages/ajax.jsp", [ "action" ], [ "2" ]);
		}
	});
	xmlhttp.open("GET", "pages/ajax.jsp?action=4&param=" + JSON.stringify(balls), true);
	xmlhttp.send();
}

function createBall() {
	var coord = field.getBoundingClientRect(); 
	var ball = {
		x : coord.left + Math.random() * (field.style.width.replace("px", "") - 50),
		y : coord.top + Math.random() * (field.style.height.replace("px", "") - 50)
	};
	return ball;
}

function drawBalls(balls) {
	for (var i = 0; i < balls.length; ++i) 
		field.appendChild(createBallHTML(balls[i]));
}

function createBallHTML(ball) {
	var node = document.createElement('div');
	node.setAttribute("class", "ball");
	node.style.left = ball.x + "px";
	node.style.top = ball.y + "px";
	return node;
}

function send(address, params, values) {
	var requestString = address + "?";
	for (var i = 0; i < params.length; ++i)
		requestString += params[i] + "=" + values[i];
	xmlhttp = getXMLHTTP(function() {
		if (this.readyState==4 && this.status==200) {
			document.getElementById("span").innerHTML += " " + this.responseText;	
			if (this.responseText.trim() === "true") {
				clearInterval(intervalId);
				outputCount();
			}				
		}
	});
	xmlhttp.open("GET", requestString, true);
	xmlhttp.send();
	intervalId = setInterval(sendRequest, 1000);	
}

function outputCount() {
	xmlhttp = getXMLHTTP(function() {
		if (this.readyState==4 && this.status==200) 
			continueWork(this.responseText);			
	});
	xmlhttp.open("GET", "pages/ajax.jsp?action=3", true);
	xmlhttp.send();
}

function continueWork(response) {
	document.getElementById("span").innerHTML = response;
	
}

function sendRequest() {
	xmlhttp.open("GET", "pages/ajax.jsp?action=2", true);
	xmlhttp.send();
}